/*
 * Copyright (c) Created by T C L on 2019.7.6.
 */

package cn.mumzone.pos.ui.dialog;

import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.R;
import cn.mumzone.pos.event.TimesCardRefreshEvent;
import cn.mumzone.pos.model.ReturnEntity;
import cn.mumzone.pos.model.TimeCardEntity;
import cn.mumzone.pos.ui.adapter.ADA_ReturnMoneyDetail;
import cn.mumzone.pos.util.BillUtil;
import cn.mumzone.pos.util.print.PrintPayTypeEntity;
import cn.mumzone.pos.util.print.PrinterService;

public class TimesCardReturnSuccessDialogFragment extends DialogFragment {

    @BindView(R.id.rv_return_money)
    RecyclerView rvReturnMoney;
    private String cardId;
    private List<ReturnEntity> returnMoney;

    private String memberPhone;

    private TimeCardEntity timeCardEntity;

    @Override
    public void onStart() {
        super.onStart();
        getDialog().setCanceledOnTouchOutside(false);//点击外部不消失
        // 设置SelectPicPopupWindow弹出窗体的背景
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        window.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparent)));
        params.gravity = Gravity.CENTER;
        params.width = DisplayUtil.dip2px(getActivity(), 438);
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cardId = getArguments().getString("cardId");
        returnMoney = (List<ReturnEntity>) getArguments().getSerializable("money");
        memberPhone = getArguments().getString("memberPhone");
        timeCardEntity = (TimeCardEntity) getArguments().getSerializable("timeCardEntity");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_times_card_return_success, container, false);
        ButterKnife.bind(this, view);

        for (ReturnEntity entity : returnMoney) {
            if (entity.getPayType().equals(BillUtil.PAY_TYPE_CASH)) {
                PrinterService.openDrawer(getContext());
                break;
            }
        }

        rvReturnMoney.setLayoutManager(new LinearLayoutManager(getContext()));
        rvReturnMoney.setHasFixedSize(true);
        ADA_ReturnMoneyDetail adapter = new ADA_ReturnMoneyDetail(getContext());
        rvReturnMoney.setAdapter(adapter);

//        if (returnMoney.size() == 1) {
//            tvReturnMoney.setText("共退款" + StringUtils.getFormattedMoneyWithUnit(returnMoney.get(0).getMoney()) + "元，已原路退还~");
//        } else {
        List<PrintPayTypeEntity> payTypeEntities = new ArrayList<>();
        double totalAmount = 0.0;
        for (ReturnEntity entity : returnMoney) {
            PrintPayTypeEntity payTypeEntity = new PrintPayTypeEntity();
            if (BillUtil.PAY_TYPE_BALANCE.equals(entity.getPayType())) {
                payTypeEntity.setName("余额退款:");
            } else if (BillUtil.PAY_TYPE_INTEGRAL.equals(entity.getPayType())) {
                payTypeEntity.setName(String.format("%s%s退款:", BigDecimalUtil.getNumber(entity.getIntegral()),
                        BillUtil.getSimplePayType(entity.getPayType())));
            } else {
                payTypeEntity.setName(String.format("%s退款:", BillUtil.getSimplePayType(entity.getPayType())));
            }
            if (!StringUtils.isEmpty(entity.getSysPayCnl()) && entity.getSysPayCnl().equals("1")) {
                payTypeEntity.setAmount(StringUtils.getFormattedMoneyWithUnit(entity.getMoney()) + "（2个工作日退还）");
            } else if (entity.getPayType().equals(BillUtil.PAY_TYPE_BANK)) {
                payTypeEntity.setAmount(StringUtils.getFormattedMoneyWithUnit(entity.getMoney()) + "（请走线下退款）");
            } else if (entity.getPayType().equals(BillUtil.PAY_TYPE_INTEGRAL)) {
                payTypeEntity.setAmount(StringUtils.getFormattedMoneyWithUnit(entity.getMoney()) + "（抵现积分不退还）");
            } else {
                payTypeEntity.setAmount(StringUtils.getFormattedMoneyWithUnit(entity.getMoney()));
            }
            payTypeEntities.add(payTypeEntity);
            totalAmount = BigDecimalUtil.add(String.valueOf(totalAmount), entity.getMoney());
        }
        PrintPayTypeEntity totalEntity = new PrintPayTypeEntity();
        totalEntity.setName("共退款：");
        totalEntity.setAmount(StringUtils.getFormattedMoneyWithUnit(String.valueOf(totalAmount)));
        payTypeEntities.add(0, totalEntity);
        adapter.update(payTypeEntities);
//        }
        return view;
    }

    @OnClick(value = {R.id.iv_close, R.id.tv_see_times_card_info, R.id.tv_know})
    public void toggleEvent(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
            case R.id.tv_know:
                dismiss();
                break;
            case R.id.tv_see_times_card_info:
                TimesCardUnavailableDetailDialogFragment timesCardUnavailableDetailDialogFragment =
                        new TimesCardUnavailableDetailDialogFragment();
                Bundle bundle = new Bundle();
                bundle.putString("cardId", cardId);
                bundle.putString("memberPhone", memberPhone);
                bundle.putSerializable("timeCardEntity", timeCardEntity);
                timesCardUnavailableDetailDialogFragment.setArguments(bundle);
                timesCardUnavailableDetailDialogFragment.show(getActivity().getSupportFragmentManager(),
                        "timesCardUnavailableDetail");
                dismiss();
                break;
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        RxBus.getDefault().post(new TimesCardRefreshEvent());
    }

}
